<template>
  <div class="dashboard-container">
    <!-- 页面标题和时间筛选 -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="date-type-selector">
          <span
            v-for="type in dateTypes"
            :key="type.value"
            :class="{ active: activeDateType === type.value }"
            @click="handleDateTypeChange(type.value)"
          >
            {{ type.label }}
          </span>
        </div>
        <el-date-picker
          v-model="selectedDate"
          :type="datePickerType"
          :format="dateFormat"
          :value-format="dateFormat"
          placeholder="选择日期"
          class="date-picker"
          @change="handleDateChange"
        />
        <button class="search-btn" @click="handleSearch">搜索</button>
      </div>
    </div>

    <!-- 第二行：报警概览和指标卡片 -->
    <div class="alarm-overview-row">
      <!-- 左侧：报警图标和累计数量 -->
      <div class="alarm-indicator">
        <div class="alarm-icon">
          <svg-icon icon-class="alarm" />
        </div>
        <div class="alarm-text">
          <div class="alarm-label">累计待处理报警</div>
          <div class="alarm-count">
            <count-to
              :end-val="totalAlarms"
              :duration="2000"
              :font-size="'36px'"
              :font-weight="'700'"
              :color="'#ffffff'"
            />
          </div>
        </div>
      </div>

      <!-- 右侧：三个指标卡片 -->
      <div class="metrics-cards">
        <!-- 日指标卡片 -->
        <div class="metric-card day-card">
          <div class="card-icon day-icon">
            <span>日</span>
          </div>
          <div class="card-content">
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-label">今日报警数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="dayMetrics.todayAlarms"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-label">今日解决数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="dayMetrics.todayResolved"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
            </div>
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-label">昨日报警数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="dayMetrics.yesterdayAlarms"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-label">昨日解决数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="dayMetrics.yesterdayResolved"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
            </div>
            <div class="metric-trend">
              <span class="trend-label">报警环比:</span>
              <span class="trend-value negative">
                <count-to
                  :end-val="dayMetrics.alarmChange"
                  :duration="1500"
                  :decimals="2"
                  :font-size="'14px'"
                  :font-weight="'600'"
                  :color="'#F56C6C'"
                />%
              </span>
            </div>
          </div>
        </div>

        <!-- 月指标卡片 -->
        <div class="metric-card month-card">
          <div class="card-icon month-icon">
            <span>月</span>
          </div>
          <div class="card-content">
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-label">本月报警数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="monthMetrics.thisMonthAlarms"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-label">本月解决数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="monthMetrics.thisMonthResolved"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
            </div>
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-label">上月报警数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="monthMetrics.lastMonthAlarms"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-label">上月解决数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="monthMetrics.lastMonthResolved"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
            </div>
            <div class="metric-trend">
              <span class="trend-label">报警环比:</span>
              <span class="trend-value positive">
                <count-to
                  :end-val="monthMetrics.alarmChange"
                  :duration="1500"
                  :font-size="'14px'"
                  :font-weight="'600'"
                  :color="'#67C23A'"
                />%
              </span>
            </div>
          </div>
        </div>

        <!-- 年指标卡片 -->
        <div class="metric-card year-card">
          <div class="card-icon year-icon">
            <span>年</span>
          </div>
          <div class="card-content">
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-label">本年报警数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="yearMetrics.thisYearAlarms"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-label">本年解决数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="yearMetrics.thisYearResolved"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
            </div>
            <div class="metric-row">
              <div class="metric-item">
                <div class="metric-label">去年报警数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="yearMetrics.lastYearAlarms"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
              <div class="metric-item">
                <div class="metric-label">去年解决数量</div>
                <div class="metric-value">
                  <count-to
                    :end-val="yearMetrics.lastYearResolved"
                    :duration="1500"
                    :font-size="'16px'"
                    :font-weight="'600'"
                    :color="'#303133'"
                  />
                </div>
              </div>
            </div>
            <div class="metric-trend">
              <span class="trend-label">报警环比:</span>
              <span class="trend-value positive">
                <count-to
                  :end-val="yearMetrics.alarmChange"
                  :duration="1500"
                  :font-size="'14px'"
                  :font-weight="'600'"
                  :color="'#67C23A'"
                />%
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 第三行：状态指标 -->
    <div class="status-indicators-row">
      <div class="status-card processing-rate-card">
        <div class="status-icon orange-icon">
          <svg-icon icon-class="chart" />
        </div>
        <div class="status-content">
          <div class="status-label">累计工单处理率</div>
          <div class="status-value">
            <count-to
              :end-val="processingRate"
              :duration="2000"
              :font-size="'24px'"
              :font-weight="'700'"
              :color="'#303133'"
            />%
          </div>
        </div>
      </div>

      <div class="status-card total-alarms-card">
        <div class="status-icon blue-icon">
          <svg-icon icon-class="alarm" />
        </div>
        <div class="status-content">
          <div class="status-label">累计实际报警数量</div>
          <div class="status-value">
            <count-to
              :end-val="totalAlarms"
              :duration="2000"
              :font-size="'24px'"
              :font-weight="'700'"
              :color="'#303133'"
            />
          </div>
        </div>
      </div>

      <div class="status-card incomplete-card">
        <div class="status-icon red-icon">
          <svg-icon icon-class="alarm" />
        </div>
        <div class="status-content">
          <div class="status-label">未处理完成</div>
          <div class="status-value">
            <count-to
              :end-val="incompleteAlarms"
              :duration="2000"
              :font-size="'24px'"
              :font-weight="'700'"
              :color="'#F56C6C'"
            />
          </div>
        </div>
      </div>

      <div class="status-card complete-card">
        <div class="status-icon teal-icon">
          <svg-icon icon-class="alarm" />
        </div>
        <div class="status-content">
          <div class="status-label">已处理完成</div>
          <div class="status-value">
            <count-to
              :end-val="completeAlarms"
              :duration="2000"
              :font-size="'24px'"
              :font-weight="'700'"
              :color="'#4fdaca'"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 第四行：图表区域 -->
    <div class="charts-row">
      <!-- 左侧：环形图 -->
      <div class="charts-left">
        <div class="chart-container">
          <div class="chart-header">
            <h3>报警状态占比</h3>
          </div>
          <div class="chart-content">
            <v-chart class="chart" :option="alarmCategoryChartOption" />
          </div>
        </div>

        <div class="chart-container">
          <div class="chart-header">
            <h3>报警等级占比</h3>
          </div>
          <div class="chart-content">
            <v-chart class="chart" :option="alarmLevelChartOption" />
          </div>
        </div>
      </div>

      <!-- 右侧：柱状图 -->
      <div class="charts-right">
        <div class="chart-container">
          <div class="chart-header">
            <h3>报警状态统计</h3>
          </div>
          <div class="chart-content">
            <v-chart class="chart" :option="alarmCategoryStatsOption" />
          </div>
        </div>

        <div class="chart-container">
          <div class="chart-header">
            <h3>报警等级统计</h3>
          </div>
          <div class="chart-content">
            <v-chart class="chart" :option="alarmLevelStatsOption" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart, PieChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import VChart from "vue-echarts";
import { ElDatePicker } from "element-plus";
import CountTo from "@/components/CountTo/index.vue";
import {
  getAlarmLevelStatistics,
  getAlarmStatusStatistics,
  getAlarmStatistics,
  getAlarmStatisticsByTime,
} from "@/api/alarm/alarmStatistics";

// Register ECharts components

use([
  CanvasRenderer,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);
// 日期类型选择
const activeDateType = ref("day");
const selectedDate = ref("");

const dateTypes = reactive([
  { label: "天", value: "day" },
  { label: "月", value: "month" },
  { label: "年", value: "year" },
]);

// 计算日期选择器类型和格式
const datePickerType = computed(() => {
  switch (activeDateType.value) {
    case "day":
      return "date";
    case "month":
      return "month";
    case "year":
      return "year";
    default:
      return "date";
  }
});

const dateFormat = computed(() => {
  switch (activeDateType.value) {
    case "day":
      return "YYYY-MM-DD";
    case "month":
      return "YYYY-MM";
    case "year":
      return "YYYY";
    default:
      return "YYYY-MM-DD";
  }
});

// 处理日期类型变化
const handleDateTypeChange = (type) => {
  activeDateType.value = type;

  // 根据类型调整默认日期为当前日期
  const now = new Date();
  switch (type) {
    case "day":
      selectedDate.value = now.toISOString().split('T')[0]; // YYYY-MM-DD
      break;
    case "month":
      selectedDate.value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`; // YYYY-MM
      break;
    case "year":
      selectedDate.value = String(now.getFullYear()); // YYYY
      break;
  }
};

// 处理日期变化
const handleDateChange = (date) => {
  selectedDate.value = date;
  console.log("日期变化:", date);
};

// 加载报警统计数据
const loadAlarmStatistics = async () => {
  try {
    // statTimeType: 1-日, 2-月, 3-年
    let statTimeType = 1;
    switch (activeDateType.value) {
      case "day":
        statTimeType = 1;
        break;
      case "month":
        statTimeType = 2;
        break;
      case "year":
        statTimeType = 3;
        break;
    }

    const response = await getAlarmStatistics({ 
      statTimeType,
      statTime: selectedDate.value 
    });
    
    if (response && response.code === 200 && response.data) {
      const data = response.data;

      // 更新日指标
      if (data.todayData) {
        dayMetrics.todayAlarms = data.todayData.currentAlarmCount || 0;
        dayMetrics.todayResolved = data.todayData.currentResolvedCount || 0;
        dayMetrics.yesterdayAlarms = data.todayData.lastAlarmCount || 0;
        dayMetrics.yesterdayResolved = data.todayData.lastResolvedCount || 0;
        // 处理百分比字符串，去除 % 符号
        const todayRate = data.todayData.alarmChainGrowthRate || "0%";
        dayMetrics.alarmChange = parseFloat(todayRate.replace('%', '')) || 0;
      }

      // 更新月指标
      if (data.monthData) {
        monthMetrics.thisMonthAlarms = data.monthData.currentAlarmCount || 0;
        monthMetrics.thisMonthResolved = data.monthData.currentResolvedCount || 0;
        monthMetrics.lastMonthAlarms = data.monthData.lastAlarmCount || 0;
        monthMetrics.lastMonthResolved = data.monthData.lastResolvedCount || 0;
        // 处理百分比字符串，去除 % 符号
        const monthRate = data.monthData.alarmChainGrowthRate || "0%";
        monthMetrics.alarmChange = parseFloat(monthRate.replace('%', '')) || 0;
      }

      // 更新年指标
      if (data.yearData) {
        yearMetrics.thisYearAlarms = data.yearData.currentAlarmCount || 0;
        yearMetrics.thisYearResolved = data.yearData.currentResolvedCount || 0;
        yearMetrics.lastYearAlarms = data.yearData.lastAlarmCount || 0;
        yearMetrics.lastYearResolved = data.yearData.lastResolvedCount || 0;
        // 处理百分比字符串，去除 % 符号
        const yearRate = data.yearData.alarmChainGrowthRate || "0%";
        yearMetrics.alarmChange = parseFloat(yearRate.replace('%', '')) || 0;
      }
    }
  } catch (error) {
    console.error("加载报警统计数据失败:", error);
  }
};

// 加载报警等级统计
const loadAlarmLevelStatistics = async () => {
  try {
    const response = await getAlarmLevelStatistics({
      statTime: selectedDate.value
    });
    
    if (response && response.code === 200 && response.data) {
      const stats = response.data.alarmLevelStats || [];
      
      // 更新报警等级占比数据
      alarmLevelData.length = 0;
      stats.forEach(item => {
        if (item && item.name) {
          const name = alarmLevelNameMap[item.name] || item.name;
          const color = alarmLevelColorMap[item.name] || "#16A5B7";
          alarmLevelData.push({
            name,
            value: item.count || 0,
            color,
          });
        }
      });

      // 更新总报警数
      totalAlarms.value = response.data.totalAlarms || 0;
    }
  } catch (error) {
    console.error("加载报警等级统计失败:", error);
  }
};

// 加载报警状态统计
const loadAlarmStatusStatistics = async () => {
  try {
    const response = await getAlarmStatusStatistics({
      statTime: selectedDate.value
    });
    
    if (response && response.code === 200 && response.data) {
      const stats = response.data.alarmStatusStats || [];
      
      // 更新报警状态占比数据（用于类别占比图）
      alarmCategoryData.length = 0;
      stats.forEach(item => {
        if (item && item.name) {
          const name = item.name;
          const color = alarmStatusColorMap[item.state] || "#16A5B7";
          alarmCategoryData.push({
            name,
            value: item.count || 0,
            color,
          });
        }
      });

      // 计算已处理和未处理数量
      const processedItem = stats.find(item => item && item.state === 2);
      const unprocessedItem = stats.find(item => item && item.state === 3);
      
      completeAlarms.value = processedItem ? (processedItem.count || 0) : 0;
      incompleteAlarms.value = unprocessedItem ? (unprocessedItem.count || 0) : 0;

      // 计算处理率
      const total = response.data.totalAlarms || 0;
      if (total > 0) {
        processingRate.value = parseFloat(((completeAlarms.value / total) * 100).toFixed(2));
      } else {
        processingRate.value = 0;
      }
    }
  } catch (error) {
    console.error("加载报警状态统计失败:", error);
  }
};

// 格式化时间显示
const formatTimeLabel = (timeName) => {
  if (!timeName) return '';
  
  switch (activeDateType.value) {
    case 'day':
      // 天模式：显示小时 "10:00" -> "10时"
      const timeMatch = timeName.match(/(\d{2}):(\d{2})/);
      return timeMatch ? timeMatch[1] + '时' : '';
    case 'month':
      // 月模式：显示日期 "2025-10-08" -> "08日"
      const dayMatch = timeName.match(/\d{4}-\d{2}-(\d{2})/);
      return dayMatch ? dayMatch[1] + '日' : '';
    case 'year':
      // 年模式：显示月份 "2025-10" -> "10月"
      const monthMatch = timeName.match(/\d{4}-(\d{2})/);
      return monthMatch ? monthMatch[1] + '月' : '';
    default:
      return timeName;
  }
};

// 加载按时间的报警统计数据
const loadAlarmStatisticsByTime = async () => {
  try {
    const response = await getAlarmStatisticsByTime({
      statTime: selectedDate.value
    });
    
    console.log('按时间查询报警统计数据:', response);
    
    // 先清空图表数据
    alarmCategoryStatsData.length = 0;
    alarmLevelStatsData.length = 0;
    
    if (response && response.code === 200 && response.data) {
      const { stateStat, levelStat } = response.data;
      
      // 处理报警状态统计数据（用于报警状态统计图表）
      if (stateStat && stateStat.length > 0) {
        // 按时间分组，聚合不同状态的数据
        const timeMap = new Map();
        
        stateStat.forEach(item => {
          const time = formatTimeLabel(item.timeName);
          if (!time) return;
          
          if (!timeMap.has(time)) {
            timeMap.set(time, {
              time,
              待处理: 0,
              已处理: 0,
              已忽略: 0
            });
          }
          
          const data = timeMap.get(time);
          // 累加各状态的sum值
          data.待处理 += item.totalStatus0Sum || 0;
          data.已处理 += item.totalStatus1Sum || 0;
          data.已忽略 += item.totalStatus2Sum || 0;
        });
        
        // 更新图表数据，按时间排序
        const sortedData = Array.from(timeMap.values()).sort((a, b) => {
          const aNum = parseInt(a.time);
          const bNum = parseInt(b.time);
          return aNum - bNum;
        });
        alarmCategoryStatsData.push(...sortedData);
      }
      
      // 处理报警等级统计数据
      if (levelStat && levelStat.length > 0) {
        // 按时间分组，聚合不同等级的数据
        const timeMap = new Map();
        
        levelStat.forEach(item => {
          const time = formatTimeLabel(item.timeName);
          if (!time) return;
          
          if (!timeMap.has(time)) {
            timeMap.set(time, {
              time,
              高: 0,
              中: 0,
              低: 0
            });
          }
          
          const data = timeMap.get(time);
          data.高 += item.totalHighSum || 0;
          data.中 += item.totalMidSum || 0;
          data.低 += item.totalLowSum || 0;
        });
        
        // 更新图表数据，按时间排序
        const sortedData = Array.from(timeMap.values()).sort((a, b) => {
          const aNum = parseInt(a.time);
          const bNum = parseInt(b.time);
          return aNum - bNum;
        });
        alarmLevelStatsData.push(...sortedData);
      }
    }
  } catch (error) {
    console.error("加载按时间报警统计数据失败:", error);
    // 发生错误时也清空数据
    alarmCategoryStatsData.length = 0;
    alarmLevelStatsData.length = 0;
  }
};

// 加载所有数据
const loadAllData = async () => {
  try {
    loading.value = true;
    await Promise.all([
      loadAlarmStatistics(),
      loadAlarmLevelStatistics(),
      loadAlarmStatusStatistics(),
      loadAlarmStatisticsByTime(),
    ]);
  } catch (error) {
    console.error("加载数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  console.log("搜索参数:", {
    dateType: activeDateType.value,
    selectedDate: selectedDate.value,
  });
  loadAllData();
};

// 日指标数据
const dayMetrics = reactive({
  todayAlarms: 0,
  todayResolved: 0,
  yesterdayAlarms: 0,
  yesterdayResolved: 0,
  alarmChange: 0,
});

// 月指标数据
const monthMetrics = reactive({
  thisMonthAlarms: 0,
  thisMonthResolved: 0,
  lastMonthAlarms: 0,
  lastMonthResolved: 0,
  alarmChange: 0,
});

// 年指标数据
const yearMetrics = reactive({
  thisYearAlarms: 0,
  thisYearResolved: 0,
  lastYearAlarms: 0,
  lastYearResolved: 0,
  alarmChange: 0,
});

// 汇总数据
const processingRate = ref(0);
const totalAlarms = ref(0);
const incompleteAlarms = ref(0);
const completeAlarms = ref(0);

// 加载状态
const loading = ref(false);

// 报警类别占比数据（报警状态统计）
const alarmCategoryData = reactive([]);

// 报警等级占比数据
const alarmLevelData = reactive([]);

// 报警等级名称映射
const alarmLevelNameMap = {
  high: "高",
  medium: "中",
  low: "低",
};

// 报警等级颜色映射
const alarmLevelColorMap = {
  high: "#F56C6C",
  medium: "#E6A23C",
  low: "#16A5B7",
};

// 报警状态名称映射
const alarmStatusNameMap = {
  2: "已处理",
  3: "未处理",
};

// 报警状态颜色映射
const alarmStatusColorMap = {
  2: "#16A5B7",
  3: "#F56C6C",
};

// 报警类别统计数据（24小时）
const alarmCategoryStatsData = reactive([
  { time: "00时", 采集类: 8, 统计类: 0 },
  { time: "01时", 采集类: 15, 统计类: 0 },
  { time: "02时", 采集类: 6, 统计类: 0 },
  { time: "03时", 采集类: 4, 统计类: 0 },
  { time: "04时", 采集类: 18, 统计类: 0 },
  { time: "05时", 采集类: 16, 统计类: 0 },
  { time: "06时", 采集类: 7, 统计类: 0 },
  { time: "07时", 采集类: 5, 统计类: 0 },
  { time: "08时", 采集类: 9, 统计类: 0 },
  { time: "09时", 采集类: 12, 统计类: 0 },
  { time: "10时", 采集类: 8, 统计类: 0 },
  { time: "11时", 采集类: 6, 统计类: 0 },
  { time: "12时", 采集类: 10, 统计类: 0 },
  { time: "13时", 采集类: 17, 统计类: 0 },
  { time: "14时", 采集类: 14, 统计类: 0 },
  { time: "15时", 采集类: 8, 统计类: 0 },
  { time: "16时", 采集类: 6, 统计类: 0 },
  { time: "17时", 采集类: 4, 统计类: 0 },
  { time: "18时", 采集类: 3, 统计类: 0 },
  { time: "19时", 采集类: 2, 统计类: 0 },
  { time: "20时", 采集类: 1, 统计类: 0 },
  { time: "21时", 采集类: 1, 统计类: 0 },
  { time: "22时", 采集类: 0, 统计类: 0 },
  { time: "23时", 采集类: 0, 统计类: 0 },
]);

// 报警等级统计数据（24小时）
const alarmLevelStatsData = reactive([
  { time: "00时", 高: 2, 中: 6, 低: 0 },
  { time: "01时", 高: 5, 中: 10, 低: 0 },
  { time: "02时", 高: 1, 中: 5, 低: 0 },
  { time: "03时", 高: 1, 中: 3, 低: 0 },
  { time: "04时", 高: 6, 中: 12, 低: 0 },
  { time: "05时", 高: 5, 中: 11, 低: 0 },
  { time: "06时", 高: 2, 中: 5, 低: 0 },
  { time: "07时", 高: 1, 中: 4, 低: 0 },
  { time: "08时", 高: 3, 中: 6, 低: 0 },
  { time: "09时", 高: 4, 中: 8, 低: 0 },
  { time: "10时", 高: 2, 中: 6, 低: 0 },
  { time: "11时", 高: 2, 中: 4, 低: 0 },
  { time: "12时", 高: 3, 中: 7, 低: 0 },
  { time: "13时", 高: 6, 中: 11, 低: 0 },
  { time: "14时", 高: 4, 中: 10, 低: 0 },
  { time: "15时", 高: 2, 中: 6, 低: 0 },
  { time: "16时", 高: 2, 中: 4, 低: 0 },
  { time: "17时", 高: 1, 中: 3, 低: 0 },
  { time: "18时", 高: 1, 中: 2, 低: 0 },
  { time: "19时", 高: 0, 中: 2, 低: 0 },
  { time: "20时", 高: 0, 中: 1, 低: 0 },
  { time: "21时", 高: 0, 中: 1, 低: 0 },
  { time: "22时", 高: 0, 中: 0, 低: 0 },
  { time: "23时", 高: 0, 中: 0, 低: 0 },
]);

// 报警状态占比图表配置
const alarmCategoryChartOption = computed(() => ({
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b}: {c}个 ({d}%)",
  },
  legend: {
    orient: "vertical",
    right: 10,
    top: "center",
    textStyle: {
      color: "#606266",
    },
    formatter: function (name) {
      const item = alarmCategoryData.find((d) => d.name === name);
      if (!item) return name;
      const total = alarmCategoryData.reduce((sum, d) => sum + d.value, 0);
      const percentage = total > 0 ? ((item.value / total) * 100).toFixed(2) : 0;
      return `${name}: ${item.value}个 (${percentage}%)`;
    },
  },
  series: [
    {
      name: "报警状态",
      type: "pie",
      radius: ["40%", "70%"],
      center: ["40%", "50%"],
      avoidLabelOverlap: false,
      label: {
        show: false,
      },
      emphasis: {
        label: {
          show: true,
          fontSize: "14",
          fontWeight: "bold",
        },
      },
      labelLine: {
        show: false,
      },
      data: alarmCategoryData.map((item) => ({
        value: item.value,
        name: item.name,
        itemStyle: {
          color: item.color,
        },
      })),
    },
  ],
}));

// 报警等级占比图表配置
const alarmLevelChartOption = computed(() => ({
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b}: {c}个 ({d}%)",
  },
  legend: {
    orient: "vertical",
    right: 10,
    top: "center",
    textStyle: {
      color: "#606266",
    },
    formatter: function (name) {
      const item = alarmLevelData.find((d) => d.name === name);
      if (!item) return name;
      const total = alarmLevelData.reduce((sum, d) => sum + d.value, 0);
      const percentage = total > 0 ? ((item.value / total) * 100).toFixed(2) : 0;
      return `${name}: ${item.value}个 (${percentage}%)`;
    },
  },
  series: [
    {
      name: "报警等级",
      type: "pie",
      radius: ["40%", "70%"],
      center: ["40%", "50%"],
      avoidLabelOverlap: false,
      label: {
        show: false,
      },
      emphasis: {
        label: {
          show: true,
          fontSize: "14",
          fontWeight: "bold",
        },
      },
      labelLine: {
        show: false,
      },
      data: alarmLevelData.map((item) => ({
        value: item.value,
        name: item.name,
        itemStyle: {
          color: item.color,
        },
      })),
    },
  ],
}));

// 报警类别统计图表配置
const alarmCategoryStatsOption = computed(() => ({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  legend: {
    data: ["待处理", "已处理", "已忽略"],
    top: 10,
    textStyle: {
      color: "#606266",
    },
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: alarmCategoryStatsData.map((item) => item.time),
    axisLabel: {
      color: "#606266",
    },
    axisLine: {
      lineStyle: {
        color: "#E4E7ED",
      },
    },
  },
  yAxis: {
    type: "value",
    name: "数量",
    nameTextStyle: {
      color: "#606266",
    },
    axisLabel: {
      color: "#606266",
    },
    axisLine: {
      lineStyle: {
        color: "#E4E7ED",
      },
    },
    splitLine: {
      lineStyle: {
        color: "#E4E7ED",
        type: "dashed",
      },
    },
  },
  series: [
    {
      name: "待处理",
      type: "bar",
      data: alarmCategoryStatsData.map((item) => item.待处理 || 0),
      itemStyle: {
        color: "#F56C6C",
      },
    },
    {
      name: "已处理",
      type: "bar",
      data: alarmCategoryStatsData.map((item) => item.已处理 || 0),
      itemStyle: {
        color: "#67C23A",
      },
    },
    {
      name: "已忽略",
      type: "bar",
      data: alarmCategoryStatsData.map((item) => item.已忽略 || 0),
      itemStyle: {
        color: "#909399",
      },
    },
  ],
}));

// 报警等级统计图表配置
const alarmLevelStatsOption = computed(() => ({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  legend: {
    data: ["高", "中", "低"],
    top: 10,
    textStyle: {
      color: "#606266",
    },
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: alarmLevelStatsData.map((item) => item.time),
    axisLabel: {
      color: "#606266",
    },
    axisLine: {
      lineStyle: {
        color: "#E4E7ED",
      },
    },
  },
  yAxis: {
    type: "value",
    name: "数量",
    nameTextStyle: {
      color: "#606266",
    },
    axisLabel: {
      color: "#606266",
    },
    axisLine: {
      lineStyle: {
        color: "#E4E7ED",
      },
    },
    splitLine: {
      lineStyle: {
        color: "#E4E7ED",
        type: "dashed",
      },
    },
  },
  series: [
    {
      name: "高",
      type: "bar",
      stack: "total",
      data: alarmLevelStatsData.map((item) => item.高),
      itemStyle: {
        color: "#F56C6C",
      },
    },
    {
      name: "中",
      type: "bar",
      stack: "total",
      data: alarmLevelStatsData.map((item) => item.中),
      itemStyle: {
        color: "#E6A23C",
      },
    },
    {
      name: "低",
      type: "bar",
      stack: "total",
      data: alarmLevelStatsData.map((item) => item.低),
      itemStyle: {
        color: "#7bfbc8",
      },
    },
  ],
}));

// 页面初始化
onMounted(() => {
  // 初始化日期为当天
  const now = new Date();
  selectedDate.value = now.toISOString().split('T')[0];
  
  // 加载数据
  loadAllData();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background: #f1f2f5;
  height: 100%;
  overflow-y: auto;
}

.dashboard-header {
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .header-content {
    display: flex;
    align-items: center;
    gap: 16px;

    .date-type-selector {
      display: flex;
      gap: 4px;
      background: #f8f9fa;
      padding: 4px;
      border-radius: 12px;
      border: 1px solid #e9ecef;

      span {
        padding: 8px 16px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        color: #6c757d;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &.active {
          background: linear-gradient(135deg, #16a5b7, #4fdaca);
          color: white;
          box-shadow: 0 4px 12px rgba(22, 165, 183, 0.3);
        }

        &:hover:not(.active) {
          background: white;
          color: #16a5b7;
        }
      }
    }

    .date-picker {
      :deep(.el-input__wrapper) {
        border-radius: 6px;
        border: 1px solid #dcdfe6;

        &:hover {
          border-color: #16a5b7;
        }

        &.is-focus {
          border-color: #16a5b7;
          box-shadow: 0 0 0 2px rgba(22, 165, 183, 0.2);
        }
      }

      :deep(.el-input__inner) {
        font-size: 14px;
        color: #606266;
      }
    }

    .search-btn {
      padding: 10px 20px;
      background: #16a5b7;
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #4fdaca;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(22, 165, 183, 0.3);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

.alarm-overview-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;

  // 左侧：报警指示器
  .alarm-indicator {
    background: linear-gradient(135deg, #1e3a8a, #3b82f6);
    border-radius: 8px;
    padding: 24px;
    display: flex;
    align-items: center;
    gap: 20px;
    min-width: 280px;
    box-shadow: 0 4px 12px rgba(30, 58, 138, 0.3);

    .alarm-icon {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .svg-icon {
        font-size: 40px;
        color: #ffffff;
        z-index: 2;
      }

      &::before {
        content: "";
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100px;
        height: 100px;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        animation: pulse 2s infinite;
      }

      &::after {
        content: "";
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 120px;
        height: 120px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        animation: pulse 2s infinite 0.5s;
      }
    }

    .alarm-text {
      color: white;

      .alarm-label {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 8px;
        opacity: 0.9;
      }

      .alarm-count {
        font-size: 36px;
        font-weight: 700;
        line-height: 1;
      }
    }
  }

  // 右侧：指标卡片
  .metrics-cards {
    display: flex;
    gap: 16px;
    flex: 1;

    .metric-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      flex: 1;
      position: relative;

      .card-icon {
        position: absolute;
        top: 12px;
        right: 12px;
        width: 28px;
        height: 28px;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 600;
        color: white;

        &.day-icon {
          background: linear-gradient(135deg, #16a5b7, #4fdaca);
        }

        &.month-icon {
          background: linear-gradient(135deg, #409eff, #67c23a);
        }

        &.year-icon {
          background: linear-gradient(135deg, #67c23a, #85ce61);
        }
      }

      .card-content {
        margin-top: 8px;
        padding-right: 40px;

        .metric-row {
          display: flex;
          gap: 16px;
          margin-bottom: 12px;

          .metric-item {
            flex: 1;

            .metric-label {
              font-size: 12px;
              color: #909399;
              margin-bottom: 4px;
              line-height: 1.2;
            }

            .metric-value {
              font-size: 16px;
              font-weight: 600;
              color: #303133;
            }
          }
        }

        .metric-trend {
          margin-top: 16px;
          padding-top: 12px;
          border-top: 1px solid #f0f0f0;
          display: flex;
          align-items: center;
          gap: 8px;

          .trend-label {
            font-size: 12px;
            color: #909399;
          }

          .trend-value {
            font-size: 14px;
            font-weight: 600;

            &.positive {
              color: #67c23a;
            }

            &.negative {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }
}

@keyframes pulse {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 0;
  }
}

.status-indicators-row {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;

  .status-card {
    flex: 1;
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .status-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      .svg-icon {
        font-size: 28px;
        color: white;
      }

      &.orange-icon {
        background: linear-gradient(135deg, #f97316, #fb923c);
      }

      &.blue-icon {
        background: linear-gradient(135deg, #409eff, #67c23a);
      }

      &.red-icon {
        background: linear-gradient(135deg, #f56c6c, #f78989);
      }

      &.teal-icon {
        background: linear-gradient(135deg, #16a5b7, #4fdaca);
      }
    }

    .status-content {
      flex: 1;

      .status-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
        font-weight: 500;
      }

      .status-value {
        font-size: 24px;
        font-weight: 700;
        line-height: 1;
      }
    }
  }
}

.charts-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;

  .charts-left {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .charts-right {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .chart-container {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .chart-header {
      padding: 20px 20px 0 20px;
      margin-bottom: 20px;
      padding-bottom: 12px;
      border-bottom: 2px solid #f0f0f0;

      .header-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 16px;
      }

      h3 {
        font-size: 18px;
        font-weight: 600;
        color: #1a1a1a;
        margin: 0;
        position: relative;
        line-height: 1.2;

        &::before {
          content: "";
          position: absolute;
          left: -12px;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 18px;
          background: linear-gradient(135deg, #16a5b7, #4fdaca);
          border-radius: 2px;
        }
      }
    }

    .chart-content {
      padding: 20px;
      height: 300px;

      .chart {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
